package jhelp;

import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

/**
 * Created with IntelliJ IDEA.
 * User: alex
 * Date: 02.12.13
 * Time: 12:38
 * SVN $Id$
 */
public class ClientPanel extends JPanel {
    private JPanel panel1;
    private JTabbedPane tabbedPane1;
    private JTextField keyword;
    private JButton findButton;
    private JButton deleteButton;
    private JButton addButton;
    private JButton editButton;
    private JButton nextButton;
    private JButton previousButton;
    private JButton exitButton;
    private JEditorPane definitionPane;
    private JCheckBox editCheckBox;
    private JLabel label;
    private JPanel mainTab;
    private JRadioButton fileSource;
    private JRadioButton databaseSource;
    private JTextField fileName;
    private JButton fileNameSelectButton;
    private JTextField hostName;
    private JTextField port;
    private JPanel settingTab;
    private JButton connectDBButton;
    private JButton disconnectDBButton;
    private JButton copyToDBButton;
    private JLabel statusLine;
    private JHelpDataSource dataSource;
    private JFileChooser chooser;
    private Item lastKey = new Item();
    private Item lastDefinition = new Item();
    private Deque<Item> listDef = new ArrayDeque<>();


    private void setInitialStateForControls() {
        connectDBButton.setEnabled(false);
        disconnectDBButton.setEnabled(false);
        hostName.setEnabled(false);
        port.setEnabled(false);
        addButton.setEnabled(false);
        editButton.setEnabled(false);
        deleteButton.setEnabled(false);
        nextButton.setEnabled(false);
        previousButton.setEnabled(false);
        editCheckBox.setEnabled(false);
        copyToDBButton.setEnabled(false);
        keyword.setEnabled(true);
        findButton.setEnabled(true);
        if (dataSource != null && dataSource.getHostName() != null) {
            databaseSource.setSelected(true);
            if (dataSource.isConnect()) {
                disconnectDBButton.setEnabled(true);
                addButton.setEnabled(true);
                editButton.setEnabled(true);
                deleteButton.setEnabled(true);
            }
            else {
                connectDBButton.setEnabled(true);
                keyword.setEnabled(false);
                findButton.setEnabled(false);
            }
            hostName.setEnabled(true);
            port.setEnabled(true);
            fileName.setEnabled(false);
            fileNameSelectButton.setEnabled(false);
        }
        else {
            if (dataSource !=null && dataSource.isFileLoaded()) {
                keyword.setEnabled(true);
                findButton.setEnabled(true);
            }
        }
    }

    public ClientPanel(JHelpDataSource source) throws JHelpException {
        if (source == null) throw new JHelpException("Не задан объект источника данных JHelpDataSource");
        clientPanelInitGUI();
        dataSource = source;
        clientPanelInitListeners();
        setInitialStateForControls();
        fileName.setText(source.getFileName());
        port.setText(((Integer)source.getPort()).toString());
        hostName.setText(source.getHostName());
    }

    public void setStatusLine(final String status) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                statusLine.setText(status);
            }
        });
    }

    public void clientPanelInitListeners() {
        findButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String key = keyword.getText().trim();
                printNextDefinition(key);
            }
        });
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (dataSource.isConnect() && !keyword.getText().trim().equals("") && !definitionPane.getText().trim().equals("")) {
                    String key = keyword.getText().trim();
                    key = key.substring(0, (key.length() > JHelp.KEYWORD_MAX_LEN) ? JHelp.KEYWORD_MAX_LEN : key.length());
                    String def = definitionPane.getText().trim();
                    def = def.substring(0, (def.length() > JHelp.DEFINITION_MAX_LEN) ? JHelp.DEFINITION_MAX_LEN : def.length());
                    Data data = new Data(JHelp.INSERT, new Item(key), new Item[] {new Item(def)});
                    Data result = dataSource.getClient().getData(data);
                    if (result != null && result.getOperation() != JHelp.OK) {
                        setStatusLine("Ошибка при добавлении записи в базу данных");
                    } else {
                        setStatusLine("Запись добавлена");
                        if (lastKey.getItem().equalsIgnoreCase(key))  {
                            lastKey = result.getKey();
                            insertNewDef(result.getValues()[0]);
                        }
                        else {
                            lastKey = new Item();
                            lastDefinition = new Item();
                            listDef = null;
                            printNextDefinition(key);
                        }
                    }
                } else setStatusLine("Соединение с БД не установлено или новые данные не введены пользователем");
            }
        });
        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (dataSource.isConnect()) {
                    String def = definitionPane.getText().trim();
                    def = def.substring(0, (def.length() > JHelp.DEFINITION_MAX_LEN) ? JHelp.DEFINITION_MAX_LEN : def.length());
                    Item newDefinition = new Item(def);
                    newDefinition.setId(lastDefinition.getId());
                    Data data = new Data(JHelp.UPDATE, lastKey, new Item[] {newDefinition});
                    Data result = dataSource.getClient().getData(data);
                    if (result != null && result.getOperation() != JHelp.OK) {
                        setStatusLine("Ошибка при обновлении записи в базе данных");
                    } else {
                        setStatusLine("Запись обновлена");
                        lastDefinition = newDefinition;
                        keyword.setText(lastKey.getItem());
                        setNavButtonStatus();
                    }
                } else setStatusLine("Соединение с БД не установлено");
            }
        });
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (dataSource.isConnect()) {
                    Data data = new Data(JHelp.DELETE, lastKey, new Item[] {lastDefinition});
                    Data result = dataSource.getClient().getData(data);
                    if (result != null && result.getOperation() != JHelp.OK) {
                        setStatusLine("Ошибка при удалении записи из базы данных");
                    } else {
                        setStatusLine("Запись удалена");
                        deleteCurrentDefinition();
                    }
                } else setStatusLine("Соединение с БД не установлено");
            }
        });
        nextButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (lastKey.equals(keyword.getText().trim())) printNextDefinition(lastKey.getItem());
                else printNextDefinition(keyword.getText().trim());
            }
        });
        previousButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (lastKey.equals(keyword.getText().trim())) printPrevDefinition(lastKey.getItem());
                else printPrevDefinition(keyword.getText().trim());
            }
        });
        exitButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (dataSource.isConnect()) {
                    setStatusLine("Программа подключена к базе данных.  Для выхода из программы закройте сначала соединение с БД");
                    return;
                }
                System.exit(0);
            }
        });
        editCheckBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (dataSource.isConnect()) {
                    if (editCheckBox.isSelected()) {
                        setStatusLine("Включен режим редактирования определения");
                        definitionPane.setEditable(true);
                    }
                    else {
                        definitionPane.setEditable(false);
                        setStatusLine("Режим редактирования отключен");
                    }

                } else {
                    setStatusLine("В режиме файла редактирование не разрешено");
                    editCheckBox.setSelected(false);
                    editCheckBox.setEnabled(false);
                }
            }
        });
        keyword.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String key = keyword.getText().trim();
                printNextDefinition(key);
            }
        });
        databaseSource.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() instanceof JRadioButton) {
                    if (((JRadioButton) e.getSource()).isSelected()) {
                        if (dataSource != null && dataSource.isConnect()) {
                            connectDBButton.setEnabled(false);
                            disconnectDBButton.setEnabled(true);
                            setStatusLine("Вы можете отключиться от базы данных");
                        } else {
                            connectDBButton.setEnabled(true);
                            disconnectDBButton.setEnabled(false);
                            setStatusLine("Заполните данные по подключению к БД и подключитесь");
                        }
                        hostName.setEnabled(true);
                        port.setEnabled(true);
//                        userName.setEnabled(true);
//                        password.setEnabled(true);
                        fileName.setEnabled((false));
                        fileNameSelectButton.setEnabled(false);
                        copyToDBButton.setEnabled(true);
                    }
                }

            }
        });
        fileSource.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() instanceof JRadioButton) {
                    if (((JRadioButton) e.getSource()).isSelected()) {
                        if (dataSource != null && dataSource.isConnect()) {
                            setStatusLine("Сначала необходимо отключится от базы данных");
                            databaseSource.setSelected(true);
                            return;
                        } else {
                            connectDBButton.setEnabled(false);
                            disconnectDBButton.setEnabled(false);
                        }
                        editCheckBox.setEnabled(false);
                        addButton.setEnabled(false);
                        editButton.setEnabled(false);
                        deleteButton.setEnabled(false);
                        hostName.setEnabled(false);
                        port.setEnabled(false);
//                        userName.setEnabled(false);
//                        password.setEnabled(false);
                        fileNameSelectButton.setEnabled(true);
                        fileName.setEnabled(true);
                        fileName.selectAll();
                        copyToDBButton.setEnabled(false);
                        if (!dataSource.isFileLoaded()) {
                            findButton.setEnabled(false);
                            keyword.setEnabled(false);
                        } else {
                            findButton.setEnabled(true);
                            keyword.setEnabled(true);
                        }
                        setStatusLine("Для загрузки файла определений выберите новый файл или введите название файла и нажмите Enter");
                    }
                }
            }
        });
//        hostName.addPropertyChangeListener(new PropertyChangeListener() {
//            @Override
//            public void propertyChange(PropertyChangeEvent evt) {
//                //To change body of implemented methods use File | Settings | File Templates.
//            }
//        });
//        port.addPropertyChangeListener(new PropertyChangeListener() {
//            @Override
//            public void propertyChange(PropertyChangeEvent evt) {
//                //To change body of implemented methods use File | Settings | File Templates.
//            }
//        });
        connectDBButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (dataSource.getClient().connect(new String[] {hostName.getText(), port.getText()}) == JHelp.OK) {
                    dataSource.setConnectState(true);
                    connectDBButton.setEnabled(false);
                    disconnectDBButton.setEnabled(true);
                    findButton.setEnabled(true);
                    keyword.setEnabled(true);
                    editCheckBox.setEnabled(true);
                    editCheckBox.setSelected(false);
                    addButton.setEnabled(true);
                    editButton.setEnabled(true);
                    deleteButton.setEnabled(true);
                    setStatusLine("Успешно подключено в серверу");
                } else setStatusLine("Ошибка при подключении к серверу");
            }
        });
        disconnectDBButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (dataSource.isConnect() && dataSource.getClient().disconnect() != JHelp.DISCONNECT)
                    setStatusLine("Ошибка при отключении от сервера");
                else setStatusLine("Соединение отключено");
                editCheckBox.setEnabled(false);
                editCheckBox.setSelected(false);
                addButton.setEnabled(false);
                editButton.setEnabled(false);
                deleteButton.setEnabled(false);
                dataSource.setConnectState(false);
                connectDBButton.setEnabled(true);
                disconnectDBButton.setEnabled(false);
                findButton.setEnabled(false);
                keyword.setEnabled(false);
            }
        });
        fileName.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                String path = fileName.getText();
                File file = new File(path);
                if (file.exists()) {
                    if (loadFile(file) == JHelp.OK) {
                        if (dataSource.isFileLoaded()) {
                            dataSource.setFileName(path);
                            setStatusLine("Файл загружен");
                        }
                    };
                }
                else setStatusLine("Файл не существует");
            }
        });
        fileNameSelectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (chooser == null) {
                    chooser = new JFileChooser(System.getProperty("user.home"));
                    chooser.setFileFilter(new FileNameExtensionFilter("TXT file", "txt", "TXT"));
                    chooser.setDialogTitle("Выберите файл с определениями");
                }
                int result = chooser.showOpenDialog(panel1);
                if (result == JFileChooser.APPROVE_OPTION) {
                    if (loadFile(chooser.getSelectedFile()) == JHelp.OK) {
                        String file = chooser.getSelectedFile().getAbsolutePath();
                        dataSource.setFileName(file);
                        fileName.setText(file);
                        setStatusLine("Файл загружен");
                    }
                }
            }
        });
        copyToDBButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!dataSource.isFileLoaded() || ! dataSource.isConnect() || dataSource.getClient() == null) return;
                dataSource.getClient().copyFileToDB();
            }
        });
    }

    private void insertNewDef(Item item) {
        if (item == null) return;
        if (lastDefinition != null && listDef != null) listDef.offer(lastDefinition);
        lastDefinition = item;
        setNavButtonStatus();
    }

    private void deleteCurrentDefinition() {
            lastDefinition = null;
            printNextDefinition(lastKey.getItem());
    }

    private void printPrevDefinition(String key) {
        if (key == null || key.equals("")) return;
        key = key.substring(0, (key.length() > JHelp.KEYWORD_MAX_LEN) ? JHelp.KEYWORD_MAX_LEN : key.length());
        if (!key.equalsIgnoreCase(lastKey.getItem())) {
            printNextDefinition(key);
            return;
        } else {
            if (listDef != null) {
                if (lastDefinition != null) listDef.offerFirst(lastDefinition);
                lastDefinition = listDef.pollLast();
                setNavButtonStatus();
            } else {
                listDef = null;
                lastDefinition = new Item();
                lastKey = new Item();
                setNavButtonStatus();
            }
        }
        if (listDef != null) {
            if (lastDefinition != null) {
                definitionPane.setText(lastDefinition.getItem());
                keyword.setText(lastKey.getItem());
            } else {
                definitionPane.setText("");
                keyword.setText("");
            }
        }
        else {
            definitionPane.setText("Определение не найдено");
        }
    }

    private void printNextDefinition(String key) {
        if (key == null || key.equals("")) return;
        key = key.substring(0, (key.length() > JHelp.KEYWORD_MAX_LEN) ? JHelp.KEYWORD_MAX_LEN : key.length());
        if (!key.equalsIgnoreCase(lastKey.getItem())) {
            Data data = dataSource.getClient().getDefinitions(key);
            if (data != null && data.getValues().length > 0) {
                lastKey = data.getKey();
                listDef = new ArrayDeque<>(Arrays.asList(data.getValues()));
                lastDefinition = listDef.poll();
                setNavButtonStatus();
            } else {
                listDef = null;
                lastDefinition = new Item();
                lastKey = new Item();
                setNavButtonStatus();
            }
        } else {
            if (listDef != null) {
                if (lastDefinition != null) listDef.offer(lastDefinition);
                lastDefinition = listDef.poll();
                setNavButtonStatus();
            } else {
                lastDefinition = new Item();
                lastKey = new Item();
                setNavButtonStatus();
            }
        }
        if (listDef != null) {
            if (lastDefinition != null) {
                definitionPane.setText(lastDefinition.getItem());
                keyword.setText(lastKey.getItem());
            } else {
                definitionPane.setText("");
                keyword.setText("");
            }

        }
        else {
            definitionPane.setText("Определение не найдено");
        }
    }

    private void setNavButtonStatus() {
        if (listDef != null && listDef.size() > 0) {
            nextButton.setEnabled(true);
            previousButton.setEnabled(true);
        } else {
            nextButton.setEnabled(false);
            previousButton.setEnabled(false);
        }
    }

    private int loadFile(File file) {
        if (file == null) return JHelp.ERROR;
        int response = dataSource.getClient().loadDefinitionFile(file);
        if (response == JHelp.OK) {
            if (dataSource.isFileLoaded()) {
                keyword.setEnabled(true);
                findButton.setEnabled(true);
                lastKey = new Item();
                lastDefinition = new Item();
                listDef = null;
            }
        }

        return response;
    }

    private void clientPanelInitGUI() {
        panel1 = new JPanel();
        panel1.setLayout(new GridLayoutManager(2, 1, new Insets(5, 5, 5, 5), -1, -1));
        panel1.setMinimumSize(new Dimension(750, 400));
        panel1.setPreferredSize(new Dimension(750, 400));
        tabbedPane1 = new JTabbedPane();
        panel1.add(tabbedPane1, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, new Dimension(200, 350), null, 0, false));
        mainTab = new JPanel();
        mainTab.setLayout(new GridLayoutManager(5, 3, new Insets(5, 5, 5, 5), -1, -1));
        tabbedPane1.addTab("Главная", mainTab);
        label = new JLabel();
        label.setText("Термин");
        mainTab.add(label, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        findButton = new JButton();
        findButton.setActionCommand("findAction");
        findButton.setText("Искать");
        mainTab.add(findButton, new GridConstraints(0, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        final JPanel panel2 = new JPanel();
        panel2.setLayout(new FormLayout("fill:d:grow", "center:max(d;4px):noGrow,top:4dlu:noGrow,center:max(d;4px):noGrow,top:4dlu:noGrow,center:max(d;4px):noGrow"));
        mainTab.add(panel2, new GridConstraints(1, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
        addButton = new JButton();
        addButton.setActionCommand("addAction");
        addButton.setText("Добавить");
        CellConstraints cc = new CellConstraints();
        panel2.add(addButton, cc.xy(1, 1));
        editButton = new JButton();
        editButton.setActionCommand("editAction");
        editButton.setText("Обновить");
        panel2.add(editButton, cc.xy(1, 3));
        deleteButton = new JButton();
        deleteButton.setActionCommand("deleteAction");
        deleteButton.setText("Удалить");
        panel2.add(deleteButton, cc.xy(1, 5));
        final JPanel panel3 = new JPanel();
        panel3.setLayout(new FormLayout("fill:d:grow", "center:d:noGrow,top:4dlu:noGrow,center:max(d;4px):noGrow"));
        mainTab.add(panel3, new GridConstraints(2, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
        nextButton = new JButton();
        nextButton.setActionCommand("nextAction");
        nextButton.setText("Следующий");
        panel3.add(nextButton, cc.xy(1, 1));
        previousButton = new JButton();
        previousButton.setActionCommand("previousAction");
        previousButton.setText("Предыдущий");
        panel3.add(previousButton, cc.xy(1, 3));
        exitButton = new JButton();
        exitButton.setActionCommand("exitAction");
        exitButton.setText("Выход");
        mainTab.add(exitButton, new GridConstraints(4, 2, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        editCheckBox = new JCheckBox();
        editCheckBox.setActionCommand("changeEditMode");
        editCheckBox.setText("Режим редактирования статьи");
        mainTab.add(editCheckBox, new GridConstraints(4, 1, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        final JScrollPane scrollPane1 = new JScrollPane();
        mainTab.add(scrollPane1, new GridConstraints(1, 0, 3, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
        definitionPane = new JEditorPane();
        definitionPane.setContentType("text/plain");
        definitionPane.setDragEnabled(false);
        definitionPane.setEditable(false);
        definitionPane.setMinimumSize(new Dimension(600, 400));
        definitionPane.setPreferredSize(new Dimension(800, 600));
        definitionPane.putClientProperty("JEditorPane.honorDisplayProperties", Boolean.FALSE);
        scrollPane1.setViewportView(definitionPane);
        keyword = new JTextField();
        keyword.setEditable(true);
        mainTab.add(keyword, new GridConstraints(0, 1, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        settingTab = new JPanel();
        settingTab.setLayout(new GridLayoutManager(2, 3, new Insets(5, 5, 5, 5), -1, -1));
        tabbedPane1.addTab("Установки", settingTab);
        final JPanel panel4 = new JPanel();
        panel4.setLayout(new GridLayoutManager(4, 4, new Insets(5, 5, 5, 5), -1, -1));
        settingTab.add(panel4, new GridConstraints(0, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, new Dimension(400, -1), new Dimension(400, -1), null, 0, false));
        panel4.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), null));
        hostName = new JTextField();
        hostName.putClientProperty("html.disable", Boolean.TRUE);
        panel4.add(hostName, new GridConstraints(0, 1, 1, 3, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        port = new JTextField();
        port.putClientProperty("html.disable", Boolean.TRUE);
        panel4.add(port, new GridConstraints(1, 1, 1, 3, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        final JLabel label1 = new JLabel();
        label1.setText("Порт сервера");
        panel4.add(label1, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        final JLabel label2 = new JLabel();
        label2.setText("Сервер приложения");
        panel4.add(label2, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        disconnectDBButton = new JButton();
        disconnectDBButton.setActionCommand("disconnectDB");
        disconnectDBButton.setText("Отключиться");
        panel4.add(disconnectDBButton, new GridConstraints(3, 3, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        connectDBButton = new JButton();
        connectDBButton.setActionCommand("connectDB");
        connectDBButton.setText("Подключиться");
        panel4.add(connectDBButton, new GridConstraints(3, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        final JPanel panel5 = new JPanel();
        panel5.setLayout(new GridLayoutManager(3, 2, new Insets(5, 5, 5, 5), -1, -1));
        settingTab.add(panel5, new GridConstraints(1, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, new Dimension(400, -1), new Dimension(400, -1), null, 0, false));
        panel5.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), null));
        fileName = new JTextField();
        fileName.putClientProperty("html.disable", Boolean.TRUE);
        panel5.add(fileName, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_NORTHWEST, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(150, -1), null, 0, false));
        copyToDBButton = new JButton();
        copyToDBButton.setActionCommand("copyToDB");
        copyToDBButton.setText("Копировать в базу данных");
        panel5.add(copyToDBButton, new GridConstraints(1, 0, 2, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        fileNameSelectButton = new JButton();
        fileNameSelectButton.setActionCommand("fileNameSelect");
        fileNameSelectButton.setText("...");
        panel5.add(fileNameSelectButton, new GridConstraints(0, 1, 2, 1, GridConstraints.ANCHOR_NORTH, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        fileSource = new JRadioButton();
        fileSource.setActionCommand("fileSelect");
        fileSource.setSelected(true);
        fileSource.setText("Из файла");
        settingTab.add(fileSource, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        databaseSource = new JRadioButton();
        databaseSource.setActionCommand("databaseSelect");
        databaseSource.setSelected(false);
        databaseSource.setText("База данных");
        settingTab.add(databaseSource, new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
        final JPanel panel6 = new JPanel();
        panel6.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
        panel1.add(panel6, new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_FIXED, new Dimension(-1, 20), new Dimension(-1, 20), new Dimension(-1, 20), 0, false));
        statusLine = new JLabel();
        statusLine.setFocusable(false);
        statusLine.setText("OK");
        panel6.add(statusLine);
        ButtonGroup buttonGroup;
        buttonGroup = new ButtonGroup();
        buttonGroup.add(databaseSource);
        buttonGroup.add(fileSource);
        fileSource.setSelected(true);
    }

    public JPanel getRoot() {
        return panel1;
    }
}
